# -*- coding:utf-8 -*-
# created by jinss

db_file = "student_data.db"

def validate_phone(num):
    if not num.isdigit():
        exit("手机号必须是数字")
    if len(num) != 11:
        exit("手机号必须是11位")

def register_api():
    stu_data = {}
    print("欢迎来到我的世界".center(50, "-"))
    print("请完成学籍注册")

    name = input("姓名：").strip()
    age = input("年龄：").strip()
    phone = input("手机号：").strip()
    if phone in phone_list:
        exit("该手机号已注册")

    validate_phone(phone)

    id_num = input("身份证号：").strip()
    if id_num in id_num_list:
        exit("该身份证号已注册")

    course_list = ["Python开发", "Java开发", "C语言开发", "MySQL", "Linux", "Go开发"]

    for index, course in enumerate(course_list):
        print(f"{index}. {course}")

    selected_course = input("选择报名的课程：")
    if selected_course.isdigit():
        selected_course = int(selected_course)
        if selected_course >=0 and selected_course < len(course_list):
            picked_course = course_list[selected_course]
        else:
            exit("不合法的选项...")
    else:
        exit("非法输入...")

    stu_data["name"] = name
    stu_data["age"] = age
    stu_data["phone"] = phone
    stu_data["id_num"] = id_num
    stu_data["course"] = picked_course

    return stu_data

def commit_to_db(filename, stu_data):
    '''
    把学员数据存到文件中
    :param filename:学员数据库文件
    :param stu_data: 学员信息
    :return:
    '''

    f = open(filename, mode="a", encoding="utf-8")
    row = f"{stu_data['name']},{stu_data['age']},{stu_data['phone']},{stu_data['id_num']},{stu_data['course']}\n"
    f.write(row)
    f.close()

def load_validate_data(filename):
    f = open("student_data.db", encoding="utf-8")
    phone_list = []
    id_num_list = []
    for line in f:
        line = line.split(",")
        phone = line[2]
        id_num = line[3]
        phone_list.append(phone)
        id_num_list.append(id_num)

    return phone_list, id_num_list


phone_list, id_num_list = load_validate_data(db_file)
stu_data = register_api()
commit_to_db(db_file, stu_data)